package 网络编程.tcpEchoServerClient;

import java.net.*;
import java.io.*;
import java.util.Scanner;

/*
实现回显服务器-客户端
利用 TCP 协议
 */
public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient() throws IOException {
        // 创建 Socket 对象的时候, 需要知道服务器的位置, 来和服务器建立连接
        socket = new Socket("127.0.0.1", 6666);
    }

    public void start() throws IOException {
        Scanner in = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);

            while (true) {
                System.out.print("> ");
                // 1. 写请求
                String request = in.next();
                // 2. 发送请求
                printWriter.println(request); // 写完请求再输入换行
                printWriter.flush();
                // 3. 等待响应
                String response = scanner.next();

                System.out.printf("request : %s  |  response : %s\n", request, response);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient();
        client.start();
    }
}
